package interceptor

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
	"ylb/tool"
	"ylb/vo"
)

//防止重复提交
func RepeatJobPost() gin.HandlerFunc {

	return func(context *gin.Context) {
		session := sessions.Default(context)

		userId := session.Get("userId")
		var job vo.JobInsertVo
		//此处消耗值
		context.BindJSON(&job)
		context.Set("jobInsertVo", job)

		key := "jobInsert:" + strconv.Itoa(userId.(int)) + ":" + job.Name
		con := tool.GetRedisConnection()
		//查询redis是否存在该用户添加的job
		_, err := con.Get(key).Result()

		if err != nil {
			//如果没有,则代表可以insert

			//五秒过期
			con.Set(key, "", time.Second*5)
			context.Next()
			return

		} else {
			//拒绝insert
			context.JSON(http.StatusOK, tool.Error("添加操作过于频繁", nil))
			context.Abort()
			return
		}
	}
}
